/**
 * students文件操作
 * 提供对students文件增删查改的API
 */

/**
 * 获取所有学生
 * 
 * 返回一个prommise对象，当读取文件成功的时候resolve数据，读取不成功的时候，resolve undefined
 */
const fs = require("fs");
const mongoose = require("mongoose");


// 连接数据库

mongoose.connect('mongodb://localhost/' + "itcast", { useNewUrlParser: true });
var db = mongoose.connection;
var studentsSchema = new mongoose.Schema({
    id: Number,
    name: String,
    gender: Number,
    age: Number,
    hobbies: String
});
let Students = mongoose.model('students', studentsSchema);
function connectMongoDB (model, callback) {
    // db.on('error', console.error.bind(console, 'connection error:'));
    // db.once('open', function () {
    //     // we're connected!
        // console.log("连接成功");
        model.find(function (err, data) {
            callback(err, data);
        })
    // });
}

function getAllStudents() {
    return new Promise((resolve, reject) => {
        // // 从文件中读取
        // fs.readFile("./db.json", "utf8", function (err, data) {
        //     if (err) {
        //         return reject(err);
        //     }
        //     resolve(JSON.parse(data));
        // })
        // // 从mongodb数据库中读取
        Students.find(function (err, data) {
            if(err) reject(err)
            resolve(data)
        })

    }).catch(function (err) {
        console.log(err)
    })
}

/**
 * 写入所有学生信息
 * @param {obj} obj 
 * 返回一个promise对象，当文件读取写入成功的时候，resolve一个success，否则resolve一个undefined
 */

function writeStudents(students) {
    return new Promise((resolve, reject) => {
        fs.writeFile("./db.json", JSON.stringify(students), (err) => {
            if (err)
                reject(err);
            resolve("success")
        })
    }).catch(function (err) {
        console.log(err)
    })
}

/**
 * 添加学生
 */

async function addStudent(student) {
    let students = await getAllStudents();
    if (!students)
        return Promise.resolve("添加失败")
    students.push(student);
    let state = await writeStudents(students);
    if (state) {
        return Promise.resolve("success")
    }
    return Promise.resolve(undefined)
}
/**
 * 修改某个学生信息
 */
async function modifyStudent(student) {
    let students = await getAllStudents();
    if (!students)
        return Promise.resolve("添加失败")
    students.forEach(element => {
        if (element.id === student.id) {
            Object.assign(element, students)
        }
    });
    let state = await writeStudents(students);
    if (state) {
        return Promise.resolve("success")
    }
    return Promise.resolve(undefined)
}

/**
 * 删除某个学生
 */

async function deleteStudent(id) {
    let students = await getAllStudents();
    if (!students)
        return Promise.resolve("添加失败")
    let delIndex = -1;
    students.forEach((element, index) => {
        if (element.id === student.id) {
            delIndex = index;
        }
    });
    if (delIndex !== -1) {
        students.splice(delIndex, 1);
    }
    let state = await writeStudents(students);
    if (state) {
        return Promise.resolve("success")
    }
    return Promise.resolve(undefined);
}
module.exports = {
    getAllStudents,
    writeStudents,
    addStudent,
    modifyStudent,
    deleteStudent
}
